const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const dotenv = require('dotenv');
const { connectDB } = require('./config/db');
const { initDB } = require('./models');

dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET;

// 连接数据库
connectDB();

// 初始化数据库表
initDB();

// 中间件
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(express.static(path.join(__dirname, 'public')));

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public/uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage });

// 导入路由
const authRoutes = require('./routes/auth');
const aiRoleRoutes = require('./routes/aiRole');
const interactionRoutes = require('./routes/interaction');
const uploadRoutes = require('./routes/upload');
const favoriteRoutes = require('./routes/favorite');
const sharedImageRoutes = require('./routes/sharedImage');
const apiKeyRoutes = require('./routes/apiKey');
const etApiKeyRoutes = require('./routes/etApiKey');
const adminRoutes = require('./routes/admin');
const userRoutes = require('./routes/user');

// 使用路由
app.use('/api/auth', authRoutes);
app.use('/api/airoles', aiRoleRoutes);
app.use('/api/interactions', interactionRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/favorites', favoriteRoutes);
app.use('/api/shared-images', sharedImageRoutes);
app.use('/api/api-keys', apiKeyRoutes);
app.use('/api/et', etApiKeyRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/users', userRoutes);

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});